package com.sleep.ws.server.config;

import com.sleep.ws.server.WsServer;
import com.sleep.ws.server.domain.WsServerProperties;
import io.netty.channel.ChannelFuture;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.AutoConfiguration;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * @author Sleep-6000
 * @date 2024/3/21
 */
@AutoConfiguration
public class WsServerAutoStartConfig implements CommandLineRunner {
    private final static String ADDRESS = "0.0.0.0";

    @Resource
    private WsServerProperties nettyServerProperties;

    @Resource
    private WsServer wsServer;

    @Override
    public void run(String... args) {
        InetSocketAddress address = new InetSocketAddress(ADDRESS, Integer.parseInt(nettyServerProperties.getPort()));
        ChannelFuture future = wsServer.run(address);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                wsServer.destroy();
            }
        });
        future.channel().closeFuture().syncUninterruptibly();
    }

}
